from flask import jsonify, request, session

from models import db
from models.index import Comment, CommentLike, User
from views import comment_blu


@comment_blu.route("/jie/comment", methods=["POST"])
def news_comment():
    content = request.form.get("content")
    post_id = request.form.get("pid")
    user_id = session.get("user_id")
    # 2. 保存到数据库
    post_comment = Comment()
    post_comment.post_id = post_id
    post_comment.user_id = user_id
    post_comment.content = content
    db.session.add(post_comment)
    db.session.commit()
    ret = {
        "errno": 0,
        "errmsg": "成功"
    }
    return jsonify(ret)


@comment_blu.route('/jie/comment_like', methods=['POST'])
def comment_like():
    action = request.form.get("action")
    comment_id = request.form.get("comment_id")
    user_id = session.get('user_id')
    print('---------', action, comment_id, user_id)

    # 2. 操作数据库
    try:
        if action == "false":
            c_like = CommentLike()
            c_like.comment_id = comment_id
            c_like.user_id = user_id
            db.session.add(c_like)
            db.session.commit()

        elif action == "true":
            c_like = db.session.query(CommentLike).filter(CommentLike.user_id == user_id,
                                                          CommentLike.comment_id == comment_id).first()
            db.session.delete(c_like)
            db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "点赞成功"
        }

        return jsonify(ret)

    except Exception as ret:
        ret = {
            "errno": 1008,
            "errmsg": "点赞失败"
        }

        return jsonify(ret)
